package cn.harry.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author harry
 * @公众号 Harry技术
 * Spring Boot 3 集成 Spring Security（1） 认证: https://blog.csdn.net/qq_35098526/article/details/144029420
 *  文章配套代码 相关配置
 */
//@Configuration
//@EnableWebSecurity
public class SecurityConfig_1 {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        // 公开访问
                        .requestMatchers("/").permitAll()
                        // 其他接口需认证
                        .anyRequest().authenticated()
                )
//                // 使用默认的登录页面
//                .formLogin(Customizer.withDefaults())
                .formLogin(
                        auth -> auth
                                .loginPage("/mylogin")
                                .loginProcessingUrl("/login")
                                .permitAll()
                )

                // 关闭 CSRF 防护
//                .csrf(csrf -> csrf.disable())

                // 使用 HTTP Basic 认证
                .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        // 创建用户
        UserDetails user = User.builder()
                .username("admin")
                .password(passwordEncoder.encode("123456"))
                .roles("ROOT")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 进行密码加密
        return new BCryptPasswordEncoder();
    }
}
